const fs = require('fs');
const path = require('path');
const http = require('http');
const mime = require('mime');
const { print } = require('idiv-utils');

const port = 3001;
const cache = {};
const chatServer = require('./lib/chat.js');

function send404(res) {
	res.writeHead(404, { 'Content-Type': 'text/plain' });
	res.write('404, Not found the resource');
	res.end();
}

function sendFile(res, filePath, fileContents) {
	res.writeHead(200, { 
		'Content-Type': mime.lookup(path.basename(filePath)) 
	});

	res.end(fileContents);
}

function serviceStatic(res, cache, absPath) {
	if(cache[absPath]) {
		sendFile(res, absPath, cache[absPath]);
	} else {
		// fs.exists(absPath, function (exists) {
		// 	if(exists) {
		// 		fs.readFile(absPath, function (err, data) {
		// 			if(err) {
		// 				send404(res);
		// 			} else {
		// 				cache[absPath] = data;
		// 				sendFile(res, absPath, data);
		// 			}
		// 		})
		// 	} else {
		// 		send404(res);
		// 	}
		// });

		fs.readFile(absPath, function (err, data) {
			if(err) {
				send404(res);
			} else {
				cache[absPath] = data;
				sendFile(res, absPath, data);
			}
		});
	}
}

const server = http.createServer();
const appPath = process.cwd();
const getAbsPath = relectivePath => path.resolve(appPath, relectivePath);

server.on('request', function (req, res) {
	var filePath = '';
	if(req.url === '/') {
		filePath = getAbsPath('public/index.html');
	} else {
		filePath = getAbsPath('public/' + req.url);
	}
	serviceStatic(res, cache, filePath);
});

server.listen(port, function () {
	print(`服务器在${ port }端口启动`)
});

// 给它提供一个配置好的http服务器, 让他们共享同一个TCP/IP端口
chatServer.listen(server);